package com.kyh.util;

import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.interfaces.RSAPrivateKey;
import java.util.Enumeration;

public class RsaUtil {
	
	/**
	 * 获取文件的私钥
	 * @param keyPath
	 * @param passwd
	 * @return
	 * @throws Exception
	 */
	public static RSAPrivateKey getPrivateKey(String keyPath, String passwd) throws Exception {
		System.out.println("秘钥文件绝对路径-----" + keyPath);

		//Class<?> c = Class.forName("com.sun.net.ssl.internal.ssl.Provider");
		//Provider provider = (Provider)c.newInstance();
		//KeyStore ks = KeyStore.getInstance("PKCS12",provider);
		PrivateKey prikey;
		KeyStore ks = KeyStore.getInstance("PKCS12");
		FileInputStream fis = new FileInputStream(keyPath);

		char[] nPassword = null;
		if ((passwd == null) || passwd.trim().equals("")) {
			nPassword = null;
		} else {
			nPassword = passwd.toCharArray();
		}
		ks.load(fis, nPassword);
		fis.close();

		Enumeration<String> enumq = ks.aliases();
		String keyAlias = null;
		if (enumq.hasMoreElements()) {
			keyAlias = (String) enumq.nextElement();
		}

		prikey = (PrivateKey) ks.getKey(keyAlias, nPassword);

		return (RSAPrivateKey) prikey;
	}
}
